/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view.GUI.sidepanels;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.AbstractCellEditor;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import model.graphic.locations.AbsoluteLocation;
import model.graphic.locations.Location;

/**
 *
 * @author Arfeniel
 */
public class LocationEditor extends AbstractCellEditor
        implements TableCellEditor,
        ActionListener {

    Location loc;
    String backup;
    EditableTextField textf;

    public LocationEditor() {
        loc = new AbsoluteLocation();
        textf = new EditableTextField("");
        textf.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e) {
        textf = (EditableTextField) e.getSource();
        Pattern p = Pattern.compile("[,\\s]+");
        String input = textf.getText().trim();
        Matcher m = p.matcher(input);
        if (m.find()) {
            Pattern psplit = Pattern.compile("[,\\s]+");
            String[] coords = psplit.split(input);
            try {
                int x = Integer.parseInt(coords[0].trim());
                int y = Integer.parseInt(coords[1].trim());
                if (x >= 0 && y >= 0 ){
                    loc.setXY(x, y);
                }
            } catch (NumberFormatException nfe) {
                //System.out.println("Deze input is niet te mappen op een locatie!");
            }

        }

        fireEditingStopped(); //Make the renderer reappear.
    }

    //Implement the one CellEditor method that AbstractCellEditor doesn't.
    public Object getCellEditorValue() {
        return loc;
    }

    //Implement the one method defined by TableCellEditor.
    public Component getTableCellEditorComponent(JTable table,
            Object value,
            boolean isSelected,
            int row,
            int column) {
        loc = (Location) value;
        backup = loc.getX() + ", " + loc.getY();
        textf.setText(loc.getX() + ", " + loc.getY());
        return textf;
    }
}

